package com.hdjk.view.activity.financial;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hdjk.view.R;
import com.hdjk.view.activity.personalcenter.RiskTestListActivity;
import com.hdjk.view.activity.personalcenter.SelectPaymentActivity;
import com.hdjk.view.callback.CallBackListener;
import com.hdjk.view.config.Constant;
import com.hdjk.view.dialog.EditTextPwdDialog;
import com.hdjk.view.dialog.MyAlertDialog;
import com.hdjk.view.dialog.TextButtonDialog;
import com.hdjk.view.entity.BankEntity;
import com.hdjk.view.entity.BuyFeeAndChargeEntity;
import com.hdjk.view.entity.FundEntity;
import com.hdjk.view.entity.IfastUserEntity;
import com.hdjk.view.entity.PayMethodEntity;
import com.hdjk.view.entity.ShopCarEntity;
import com.hdjk.view.network.Network;
import com.hdjk.view.network.PersonalNetWork;
import com.hdjk.view.network.TransactionNetWork;
import com.hdjk.view.util.SharedPreferencesUtil;
import com.hdjk.view.util.ToastUtils;
import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.base.BaseActivity;
import com.lst.projectlib.entity.Msg;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import static com.hdjk.view.R.id.tv_sure;

/**
 * 购物车支付页面
 * Created by sxy on 2017/11/3.
 */

public class ShopCarBuyActivity extends BaseActivity implements View.OnClickListener {

    private int riskConfirmed = 0;
    private List<ShopCarEntity> mFundList;
    private PayMethodEntity mPayMethod;
    private TextButtonDialog dialog;
    private MyAlertDialog alertDialog;
    private List<BankEntity> bankList;
    private int bankIndex = 0;
    private int payMethod = 0;

    // Content View Elements
    private com.lst.projectlib.component.CustomView.TopTitleBar ttb_title_bar;
    private RelativeLayout rel_bank;
    private ImageView iv_bank_logo;
    private TextView tv_bank_name;
    private TextView tv_number;
    private TextView tv_wh;
    private TextView tv_buy;
    private TextView tv_yifeng;
    private LinearLayout lin_content;
    // End Of Content View Elements

    private void bindViews() {
        ttb_title_bar = (com.lst.projectlib.component.CustomView.TopTitleBar) findViewById(R.id.ttb_title_bar);
        rel_bank = (RelativeLayout) findViewById(R.id.rel_bank);
        iv_bank_logo = (ImageView) findViewById(R.id.iv_bank_logo);
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_number = (TextView) findViewById(R.id.tv_number);
        tv_wh = (TextView) findViewById(R.id.tv_wh);
        tv_buy = (TextView) findViewById(R.id.tv_buy);
        tv_yifeng = (TextView) findViewById(R.id.tv_yifeng);
        lin_content = (LinearLayout) findViewById(R.id.lin_content);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_shop_car_buy);
        bindViews();
        ttb_title_bar.findViewById(R.id.tvNavBack).setOnClickListener(this);
        rel_bank.setOnClickListener(this);
        tv_buy.setOnClickListener(this);
        tv_yifeng.setOnClickListener(this);
    }

    @Override
    protected void initData() {
//        if (getIntent().getExtras().getSerializable("fund") instanceof FundEntity) {
//            mFund = (FundEntity) getIntent().getExtras().getSerializable("fund");
//            tv_currency.setText(mFund.getFundName());
//            tv_fund_code.setText(mFund.getFundCode());
//            tv_risk.setText(mFund.getRiskRateName());
//            if (!TextUtils.isEmpty(mFund.getFundStatus())) {
//                if ("0".equals(mFund.getFundStatus())) {
//                    tv_money_size.setText("（" + mFund.getMinInitialIpoAmount() + "---" + mFund.getMaxIpoAmount() + "）");
//                } else if ("1".equals(mFund.getFundStatus())) {
//                    tv_money_size.setText("（" + mFund.getMinInitialBuyAmount() + "---" + mFund.getMaxBuyAmount() + "）");
//                }
//            }
//        }
        getPayMethod();
        mFundList = (List<ShopCarEntity>) getIntent().getSerializableExtra("list");
        if (mFundList != null && mFundList.size() > 0) {
            for (ShopCarEntity entity : mFundList) {
                View view = LayoutInflater.from(this).inflate(R.layout.layout_buy_fund_info, null);
                TextView tv_currency = (TextView) view.findViewById(R.id.tv_currency);
                TextView tv_fund_code = (TextView) view.findViewById(R.id.tv_fund_code);
                TextView tv_risk = (TextView) view.findViewById(R.id.tv_risk);
                TextView tv_money = (TextView) view.findViewById(R.id.tv_money);
                FundEntity fund = entity.getFund();
                tv_currency.setText(fund.getFundName());
                tv_fund_code.setText(fund.getFundCode() + " " + fund.getFundTypeName());
                tv_risk.setText(fund.getRiskRateName());
                tv_money.setText(entity.getAmount() + "元");
                lin_content.addView(view);
                getPayFeeAndCharge(entity, view);
            }
        }
    }

    private void getPayMethod() {
        mDialog.show();
        JSONObject object = new JSONObject();
        try {
            object.put("accountNumber", UserTokenUtil.getUserName(ShopCarBuyActivity.this));
            TransactionNetWork.getPayMethod(UserTokenUtil.getToken(ShopCarBuyActivity.this), object.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof PayMethodEntity) {
                        mPayMethod = (PayMethodEntity) msg.getData();
                        if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && mPayMethod.getInvestorBankDetails().getData().size() > 0) {
                           for (int i=0;i<mPayMethod.getInvestorBankDetails().getData().size();i++){
                               if (mPayMethod.getInvestorBankDetails().getData().get(i).getPreferred().equals("Y")){
                                   setPayMethod(payMethod, mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId());
                               }
                           }
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setPayMethod(int type, String investorPayId) {
        if (mPayMethod != null) {
            if (type == 0) {//银行卡
                if (mPayMethod.getInvestorBankDetails() != null && mPayMethod.getInvestorBankDetails().getData() != null && !TextUtils.isEmpty(investorPayId)) {
                    for (int i = 0; i < mPayMethod.getInvestorBankDetails().getData().size(); i++) {
                        if (investorPayId.equals(mPayMethod.getInvestorBankDetails().getData().get(i).getInvestorPayId()))
                            bankIndex = i;
                    }
                    switch (mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode()) {
                        case "GDB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_gdb));
                            break;
                        case "ABC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_abc));
                            break;
                        case "ICBC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_icbc));
                            break;
                        case "CMBC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_cmbc));
                            break;
                        case "CEB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_ceb));
                            break;
                        case "HXBANK":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_hxbank));
                            break;
                        case "SPABANK":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_spabank));
                            break;
                        case "CIB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_cib));
                            break;
                        case "SPDB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_spdb));
                            break;
                        case "CITIC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_citic));
                            break;
                        case "COMM":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_comm));
                            break;
                        case "CMB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_cmb));
                            break;
                        case "CCB":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_ccb));
                            break;
                        case "BOC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_boc));
                            break;
                        case "PSBC":
                            iv_bank_logo.setImageDrawable(ShopCarBuyActivity.this.getResources().getDrawable(R.drawable.icon_psbc));
                            break;
                    }
                    String number = mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankNumber();
                    if (!TextUtils.isEmpty(number)) {
                        if (number.length() > 4) {
                            tv_number.setText("(" + number.substring(number.length() - 4) + ")");
                        } else {
                            tv_number.setText("(" + number + ")");
                        }
                    }
                    bankList = SharedPreferencesUtil.getBankList(ShopCarBuyActivity.this);
                    if (bankList == null || bankList.size() == 0) {
                        Network.getBankList(UserTokenUtil.getToken(ShopCarBuyActivity.this), new CallBackListener() {
                            @Override
                            public void onCallBackCompleted(Msg msg) {
                                if (msg != null) {
                                    if (msg.getSuccess()) {
                                        if (!TextUtils.isEmpty(msg.getResult()))
                                            SharedPreferencesUtil.saveBankList(ShopCarBuyActivity.this, msg.getResult());
                                        bankList = (List<BankEntity>) msg.getData();
                                        for (int i = 0; i < bankList.size(); i++) {
                                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                                tv_bank_name.setText(bankList.get(i).getName());
                                                break;
                                            }
                                        }
                                    }
                                }
                            }

                            @Override
                            public void onCallBackError(Msg msg) {
                                mDialog.cancel();
                            }
                        });
                    } else {
                        for (int i = 0; i < bankList.size(); i++) {
                            if (bankList.get(i).getBankCode().equals(mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getBankCode())) {
                                tv_bank_name.setText(bankList.get(i).getName());
                                break;
                            }
                        }
                    }
                    tv_number.setVisibility(View.VISIBLE);
                    tv_wh.setVisibility(View.VISIBLE);
                }
            } else if (type == 1) {//现金钱包
                if (mPayMethod.getInvestorCashWallets() != null && mPayMethod.getInvestorCashWallets().getData() != null) {
                    iv_bank_logo.setImageDrawable(getResources().getDrawable(R.drawable.wallet));
                    tv_bank_name.setText("现金钱包");
                    tv_number.setVisibility(View.GONE);
                    tv_wh.setVisibility(View.GONE);
                }
            }
        }
    }

    private void getPayFeeAndCharge(ShopCarEntity entity, final View view) {
        if (!TextUtils.isEmpty(entity.getAmount())) {
            double money = Double.parseDouble(entity.getAmount());
            if (money > 0) {
                JSONObject object = new JSONObject();
                try {
                    object.put("fundCode", entity.getFundCode());
                    object.put("investmentAmount", money);
                    TransactionNetWork.getBuyFeeAndCharge(UserTokenUtil.getToken(ShopCarBuyActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof BuyFeeAndChargeEntity) {
                                BuyFeeAndChargeEntity entity = (BuyFeeAndChargeEntity) msg.getData();
                                ((TextView) (view.findViewById(R.id.tv_rate))).setText(entity.getSalesChargesRate() + "%");
                                ((TextView) (view.findViewById(R.id.tv_cost))).setText(entity.getSalesCharges());
                            }
                        }

                        @Override
                        public void onCallBackError(Msg msg) {

                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            ((TextView) (view.findViewById(R.id.tv_rate))).setText("0.00%");
            ((TextView) (view.findViewById(R.id.tv_cost))).setText("0.00");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvNavBack:
                back();
                break;
            case R.id.tv_yifeng:
                showPopupWindow(tv_yifeng);
                break;
            case R.id.rel_bank:
                Intent intent = new Intent(this, SelectPaymentActivity.class);
                intent.putExtra("isWallet",false);
                startActivityForResult(intent, 61);
                break;
            case R.id.tv_buy:
                buy();
                break;
        }
    }

    private void buy() {
        mDialog.show();
        JSONObject obj = new JSONObject();
        try {
            obj.put("accountNumber", UserTokenUtil.getUserName(ShopCarBuyActivity.this));
            PersonalNetWork.getIfastUserInfo(UserTokenUtil.getToken(ShopCarBuyActivity.this), obj.toString(), new CallBackListener() {
                @Override
                public void onCallBackCompleted(Msg msg) {
                    mDialog.cancel();
                    if (msg != null && msg.getSuccess() && msg.getData() != null && msg.getData() instanceof IfastUserEntity) {
                        IfastUserEntity userEntity = (IfastUserEntity) msg.getData();
                        if (Integer.parseInt(userEntity.getRiskAppetite()) < 1) {
                            Intent intent = new Intent(ShopCarBuyActivity.this, RiskTestListActivity.class);
                            startActivity(intent);
                            ToastUtils.showShortToast(ShopCarBuyActivity.this, "您未进行风险能力测试，请先测试");
                            return;
                        }
                        boolean hasBig = false;
                        for (int i = 0; i < mFundList.size(); i++) {
                            ShopCarEntity entity = mFundList.get(i);
                            if (Integer.parseInt(userEntity.getRiskAppetite()) == 1 && Integer.parseInt(entity.getFund().getRiskRate()) > 1) {
                                ToastUtils.showShortToast(ShopCarBuyActivity.this, "您的风险等级为保守型，不能购买超过风险等级的产品");
                                return;
                            }
                            if (Integer.parseInt(entity.getFund().getRiskRate()) > Integer.parseInt(userEntity.getRiskAppetite())) {
                                hasBig = true;
                            }
                        }
                        if (hasBig) {
                            dialog = new TextButtonDialog(ShopCarBuyActivity.this, R.style.progress_dialog, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    switch (v.getId()) {
                                        case R.id.tv_cancel:
                                            dialog.dismiss();
                                            break;
                                        case tv_sure:
                                            dialog.dismiss();
                                            riskConfirmed = 1;
                                            showPwdDialog();
                                            break;
                                    }
                                }
                            });
                            dialog.setDialogContent("您所选基金的购买风险超出您的风险承受能力，确定要购买吗？", 15);
                            dialog.show();
                        } else {
                            showPwdDialog();
                        }
                    }
                }

                @Override
                public void onCallBackError(Msg msg) {
                    mDialog.cancel();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void showPwdDialog() {
        EditTextPwdDialog dialog = new EditTextPwdDialog(this, "输入密码", "", getResources().getDrawable(R.drawable.icon_input_pwd), "请输入交易密码", new EditTextPwdDialog.OnSureClickListener() {
            @Override
            public void onSureClick(String txt) {
                mDialog.show();
                JSONObject object = new JSONObject();
                try {
                    object.put("accountNumber", UserTokenUtil.getUserName(ShopCarBuyActivity.this));
                    object.put("payMethod", payMethod);
                    if (payMethod == 0) {
                        object.put("investorPayId", mPayMethod.getInvestorBankDetails().getData().get(bankIndex).getInvestorPayId());
                    }
                    object.put("password", txt);
                    JSONArray array = new JSONArray();
                    for (int i = 0; i < mFundList.size(); i++) {
                        ShopCarEntity entity = mFundList.get(i);
                        JSONObject obj = new JSONObject();
                        obj.put("currency", "156");
                        obj.put("fundCode", entity.getFund().getFundCode());
                        obj.put("investmentAmount", entity.getAmount());
                        array.put(obj);
                    }
                    object.put("purchaseFunds", array);
                    object.put("riskConfirmed", riskConfirmed);
                    TransactionNetWork.buyFund(UserTokenUtil.getToken(ShopCarBuyActivity.this), object.toString(), new CallBackListener() {
                        @Override
                        public void onCallBackCompleted(Msg msg) {
                            mDialog.cancel();
                            Message message = new Message();
                            message.what = 1;
                            message.obj = msg;
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onCallBackError(Msg msg) {
                            mDialog.cancel();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        dialog.show();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    final Msg m = (Msg) msg.obj;
                    String title = "";
                    if (m != null && m.getSuccess()) {
                        title = "购买成功";
                        Intent intent = new Intent(Constant.INTENT_FILTER_STRING_AFTER_BUY_SUCCESS);
                        sendBroadcast(intent);
                    } else {
                        if (TextUtils.isEmpty(m.getMsg())) {
                            title = "购买失败";
                        } else {
                            title = m.getMsg();
                        }
                    }
                    alertDialog = new MyAlertDialog(ShopCarBuyActivity.this, title, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (m.getSuccess()) {
                                setResult(741);
                                back();
                            }
                        }
                    });
                    alertDialog.show();
                    break;
                case 2:
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 61 && resultCode == 61) {
            String investorPayId = "";
            payMethod = data.getIntExtra("payMethod", -1);
            if (payMethod == 0) {
                investorPayId = data.getStringExtra("investorPayId");
            }
            if (payMethod >= 0) {
                setPayMethod(payMethod, investorPayId);
            }
        }
    }
}
